package com.antdesignbackend.backend.configure.dept.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.antdesignbackend.backend.entity.Users;
import com.antdesignbackend.backend.entity.tree.Ztree;
import com.antdesignbackend.backend.service.UserService;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.configure.dept.entity.Dept;
import com.antdesignbackend.backend.configure.dept.entity.entityVo.DeptVo;
import com.antdesignbackend.backend.configure.dept.service.DeptService;

/**
 * 部门管理
 *
 * @author 不二
 * @email dept
 * @date 2020-08-10 10:12:26
 */

@Controller
@RequestMapping("/dept")
@Slf4j
public class DeptController extends BaseController{

	private static final String FUN_NAME = "部门管理";//功能名称

	@Autowired
	private DeptService deptService;

	@Autowired
	private UserService userService;

	@GetMapping("/index")
	@AuthToken
	public String index() {
		return "configure/dept/index";
	}


	@PostMapping("/tableSearch")
	@ResponseBody
	List<DeptVo> tableSearch(DeptVo deptVo) throws SecurityException, IllegalArgumentException{
		QueryWrapper<DeptVo> wrapper = new QueryWrapper<>();
		if (deptVo.getDept_name() != null && !deptVo.getDept_name().equals("")){
			wrapper.like("dept_name",deptVo.getDept_name());
		}
		if (deptVo.getLeader() != null && !deptVo.getLeader().equals("")){
			wrapper.like("leader",deptVo.getLeader());
		}
		return deptService.search(wrapper,new Page<DeptVo>(1,999));

	}

	/**
	 * 加载部门列表树
	 */
	@GetMapping("/treeData")
	@ResponseBody
	public List<Ztree> treeData()
	{
		List<Dept> list = deptService.list();
		List<Ztree> ztrees = initZtree(list,null);
		return ztrees;
	}

	@GetMapping("/getById/{dept_id}")
	@ResponseBody
	public	Dept getById(@PathVariable(name = "dept_id") Long dept_id) {
		Dept obj = deptService.getById(dept_id);
		return obj;
	}

	@PostMapping("/save")
	@ResponseBody
	public ReturnVO save(@RequestBody Dept dept){
		ReturnVO result = new ReturnVO();
		//查看部门是否存在
		QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("dept_name",dept.getDept_name());
		queryWrapper.eq("parent_id",dept.getParent_id());
		List<Dept> list = deptService.list(queryWrapper);
		if (list.size() > 0 ){ //部门已存在
			result.setMessage("保存失败！");
			result.setCode("502");
			return result;
		}
		Dept info = deptService.getById(dept.getParent_id());
		if (info == null){
			result.setMessage("保存失败！");
			result.setCode("500");
			return result;
		}
		dept.setAncestors(info.getAncestors() + "," + dept.getParent_id());
		dept.setCreate_by(getLoginUserName());
		dept.setCreate_time(new Date());
		try {
			if(deptService.save(dept)){
				result.setMessage("保存成功！");
				result.setCode("200");
			}else{
				result.setMessage("保存失败！");
				result.setCode("500");
			}
		}catch (Exception e){
			log.error(e.getMessage());
			result.setMessage("保存失败！");
			result.setCode("500");
		}
		return result;
	}

	@PostMapping("update")
	@ResponseBody
	public ReturnVO updateById(@RequestBody Dept dept){
		ReturnVO result = new ReturnVO();
		//查看部门是否存在
		QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("dept_name",dept.getDept_name());
		queryWrapper.eq("parent_id",dept.getParent_id());
		queryWrapper.notIn("dept_id",dept.getDept_id());
		List<Dept> list = deptService.list(queryWrapper);
		if (list.size() > 0 ){ //部门已存在
			result.setMessage("保存失败！");
			result.setCode("502");
			return result;
		}
		//不能挂载在自己身上
		if (dept.getDept_id().equals(dept.getParent_id())){
			result.setMessage("保存失败！");
			result.setCode("503");
			return result;
		}
		//不能选择最后一个节点【此节点必须含子节点】
		QueryWrapper<Dept> wrapper = new QueryWrapper<>();
		wrapper.eq("parent_id",dept.getParent_id());
		List<Dept> depts = deptService.list(wrapper);
		if (depts.size() == 0){
			result.setMessage("保存失败！");
			result.setCode("504");
			return result;
		}
        Dept info = deptService.getById(dept.getParent_id());
		if (info != null){
			dept.setAncestors(info.getAncestors() + "," + dept.getParent_id());
		}
        dept.setUpdate_by(getLoginUserName());
        dept.setUpdate_time(new Date());
		try {
			if(deptService.updateById(dept)){
				result.setMessage("保存成功！");
				result.setCode("200");
			}else{
				result.setMessage("保存失败！");
				result.setCode("500");
			}
		}catch (Exception e){
			log.error(e.getMessage());
			result.setMessage("保存失败！");
			result.setCode("500");
		}
		return result;
	}

	/**
     * 根据id删除
     */
	@DeleteMapping("/deleteById/{id}")
	@ResponseBody
	public ReturnVO deleteById(@PathVariable Serializable id) {
        ReturnVO result = new ReturnVO();
	    //判断节点下是否存在子节点
        QueryWrapper<Dept> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dept> list = deptService.list(wrapper);
        if (list.size() > 0){
            result.setMessage("删除失败");
            result.setCode("501");
            return result;
        }
        //部门下是否还有关联的人
		QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deptId",id);
        int count = userService.count(queryWrapper);
        if (count > 0){
			result.setMessage("删除失败");
			result.setCode("502");
			return result;
		}

        try {
            if (deptService.removeById(id) ){
                result.setMessage("删除成功");
            } else {
                result.setMessage("删除失败");
                result.setCode("500");
            }
        }catch (Exception e){
            log.error(e.getMessage());
            result.setMessage("删除失败");
            result.setCode("500");
        }
		return result;
	}

	/**
	 * 对象转部门树
	 *
	 * @param deptList 部门列表
	 * @param roleDeptList 角色已存在菜单列表
	 * @return 树结构列表
	 */
	public List<Ztree> initZtree(List<Dept> deptList, List<String> roleDeptList)
	{

		List<Ztree> ztrees = new ArrayList<Ztree>();
//		boolean isCheck = StringUtils.isNotNull(roleDeptList);
		for (Dept dept : deptList)
		{
			Ztree ztree = new Ztree();
			ztree.setId(dept.getDept_id());
			ztree.setPId(dept.getParent_id());
			ztree.setName(dept.getDept_name());
			ztree.setTitle(dept.getDept_name());
//			if (isCheck)
//				{
//					ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
//				}
			ztrees.add(ztree);
		}
		return ztrees;
	}

}
